<?php
if (!function_exists('backJson')) {
    function backJson($data = [], $code = ApiConst::BACK_SUCCESS, $message = null)
    {
        exit(json_encode([
            'code' => (int)$code,
            'data' => $data,
            'msg' => $message === null ? ApiConst::BACK_MSG[$code] : $message
        ], JSON_UNESCAPED_UNICODE));
    }
}

function dump($var, $echo = true, $label = null, $flags = ENT_SUBSTITUTE)
{
    $label = (null === $label) ? '' : rtrim($label) . ':';

    ob_start();
    var_dump($var);
    $output = preg_replace('/\]\=\>\n(\s+)/m', '] => ', ob_get_clean());

    if (!extension_loaded('xdebug')) {
        $output = htmlspecialchars($output, $flags);
    }
    $output = '<pre>' . $label . $output . '</pre>';
    if ($echo) {
        echo($output);
        return;
    }

    return $output;
}

function encryptLogin($str = '')
{
    return strtoupper(md5(md5($str . '_LOGIN')));
}

function checkName($username = '')
{
    $len = strlen($username);
    if (!preg_match("/^[a-zA-Z0-9_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]+$/", $username)) {
        return false;
    } elseif (11 < $len || $len < 2) {
        return false;
    }
    return true;
}

function inputParam($name, $default = null)
{
    $data = json_decode(file_get_contents('php://input'), true);
    return isset($data[$name]) ? $data[$name] : $default;
}

function postParam($name, $default = null)
{
    return isset($_POST[$name]) ? $_POST[$name] : $default;
}

if (!function_exists('getParam')) {
    function getParam($name, $default = null)
    {
        return isset($_REQUEST[$name]) ? $_REQUEST[$name] : $default;
    }
}
trait Instance
{
    /**
     * @var null|static 实例对象
     */
    protected static $instance = null;

    /**
     * 获取示例
     * @param array $options 实例配置
     * @return static
     */
    public static function instance($options = [])
    {
        if (is_null(self::$instance)) self::$instance = new self($options);

        return self::$instance;
    }
}
